#!/bin/sh -e

if [ "x${COVERITY_SCAN_PROJECT_NAME}" != "x" ] ; then exit 0; fi

. CI/travis/lib.sh

handle_default() {
	echo "### making build dir"
	mkdir -p build
	cd build

	FLAGS="-DENABLE_PACKAGING=ON -DDEB_DETECT_DEPENDENCIES=ON -DPYTHON_BINDINGS=ON"

	echo "### cmake ${FLAGS}"
	cmake ${FLAGS} ..

	echo "### make"
	make
	if [ "$TRAVIS" = "true" ] ; then
		# make sure the *.so can be found during make package
		echo "### Installing package as root"
		sudo make install
		# get rid of anything that will cause a problem
		echo "### Deleting install_manifest.txt (created as root)"
		sudo rm ./install_manifest.txt
	fi
	if command_exists sphinx-build ; then
		# to build the python doc, libiio and py-iio need to be installed
		# so we need to re-do some minor things now that they are
		FLAGS="${FLAGS} -DWITH_DOC=ON -DWITH_MAN=ON"
		echo "### cmake ${FLAGS}"
		cmake ${FLAGS} ..
		echo "### make"
		make
	fi
	echo "### make package"
	make package
	if [ -n "${GH_DOC_TOKEN}" ] && \
			[ -f "./generateDocumentationAndDeploy.sh" ] ; then
		sh generateDocumentationAndDeploy.sh
	fi
	cd ..

	# make sure we are up to date (once)
	if [ "$LDIST" = "DO_NOT_DEPLOY" ] ; then
		./CI/travis/check_kernel.sh
	fi
	echo "### All done building"
}

handle_centos() {
	mkdir -p build
	cd build
	cmake -DENABLE_PACKAGING=ON -DPYTHON_BINDINGS=ON ..
	make
	make package
	cd ..
}

handle_centos_docker() {
	run_docker_script inside_docker.sh \
		"centos:centos${OS_VERSION}" "centos"
}

handle_ubuntu_docker() {
	run_docker_script inside_docker.sh \
		"ubuntu:${OS_VERSION}"
}

LIBNAME="$1"
OS_TYPE=${2:-default}

handle_${OS_TYPE}

